//
//  PlayerController.m
//  TribleWar
//
//  Created by ＣＳＴ ＣＳＴ on 8/8/12.
//  Copyright (c) 2012 ＣＳＴ. All rights reserved.
//

#import "PlayerController.h"
#import "GameMove.pb.h"
#import "AppDelegate.h"
#define SPEED 50
@implementation PlayerController



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        GameView_ = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
        GameView_.backgroundColor = [UIColor whiteColor];
//        GameView_.frame = CGRectMake(0, 0, 800, 800);
        players_ = [NSMutableDictionary dictionary]; 
    }     
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(moveAnchorPoint:) userInfo:(id)player1 repeats:YES];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    
    player_ = nil;
    players_ = nil;
    GameView_ = nil;
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)loadView
{
    self.view = GameView_;
    UIButton *_jumpButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _jumpButton.frame = CGRectMake(20., 20., 40., 18.);
    _jumpButton.center = CGPointMake(300, 445);
    [_jumpButton setTitle:@"退出" forState:UIControlStateNormal];
    [_jumpButton addTarget:self action:@selector(exitGame:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_jumpButton];
}

//get coordinate of the touch point 
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

    //get position of the animating layer
    CGPoint currentPosition = [[player_ presentationLayer]position];
    player_.curCoord = currentPosition;

    //set coordinate of touch to purpose coordinate
    UITouch *touch = [touches anyObject];
    CGPoint pos = [touch locationInView:self.view];
    player_.posCoord = pos;
    //[player_ moveAnchorPoint];
    
    
    NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
    int curTime = [[NSNumber numberWithDouble: timeStamp]intValue];
    
    Vector *curPos = [[[[Vector builder]setX:player_.curCoord.x]setY:player_.curCoord.y]build];
    Vector* purPos = [[[[Vector builder]setX:player_.posCoord.x]setY:player_.posCoord.y]build];
    State* state = [[[[[State builder]setCurPos:curPos]setPurPos:purPos]setCurTime:curTime]build];
    NSData* moveData = [[[[[[Move builder]setCategory:CategoryCharacter]setState:state]setUid:player_.pid ]build] data];
    NSLog(@"move ...");
    [[AppDelegate sharedAppDelegate]->netWorkHandler_ sendData:moveData Pid:PIDMove];

}

- (void)moveCallback:(Move *)move
{ 
    
    if (![self isMoveInvalid:move]) {
        return;
    }
    Sprite *_player = [players_ objectForKey:move.uid];    
    if (!_player) {
        _player = [[Sprite alloc]init];
        [_player setPid:move.uid];
        if (![self addPlayer:_player]) {
            NSLog(@"add player failed");
            return;
        }
    }
    if (move.action == ActionLogout) {
        if (![self movePlayer:_player]) {
            NSLog(@"move player failed");
            return;
        }
    }
    [_player setCurCoord:CGPointMake(move.state.curPos.x, move.state.curPos.y)];
    [_player setPosCoord:CGPointMake(move.state.purPos.x, move.state.purPos.y)];
    [_player moveAnchorPoint];

}

- (BOOL)isMoveInvalid:(Move *)move
{
    if (!move) {
        NSLog(@"move is nil");
        return NO;
    }
    if (!(move.category == CategoryCharacter)) {
        NSLog(@"move category is not CategoryCharacter");
        return NO;
    }
    if (!move.state) {
        NSLog(@"move state is nil");
        return NO;
    }
    if (!move.state.curPos) {
        NSLog(@"move curPos is nil");
        return NO;
    }
    if (move.state.curPos.x < 0.000000||move.state.curPos.y < 0.000000) {
        NSLog(@"curPos x or y is less than 0");
        return NO;
    }
    if (move.state.purPos.x < 0.000000||move.state.purPos.y < 0.000000) {
        NSLog(@"purPos x or y is less than 0");
        return NO;
    }
    return YES;
}

- (BOOL)addPlayer:(Sprite*)player
{
    if (!player) {
        return NO;
    }
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([player.pid isEqualToString: [defaults objectForKey :@"userAccount"] ]) {
        player_ = player;
    }
    [players_ setValue:player forKey:player.pid];
    [GameView_.layer addSublayer:player];
    return YES;
}

- (BOOL)movePlayer:(Sprite*)player
{
    if (!player) {
        return NO;
    }
    [players_ removeObjectForKey:player.pid];
    [player removeFromSuperlayer];
    return YES;
}

- (void)exitGame:(id)sender
{
    NSData* moveData = [[[[[[Move builder]setAction:ActionLogout] setCategory:CategoryCharacter]setUid:player_.pid ]build] data];
    
    [[AppDelegate sharedAppDelegate]->netWorkHandler_ sendData:moveData Pid:PIDMove];
    if (![self movePlayer:player_]) {
        NSLog(@"move player failed");
        return;
    }
    
    [self.view removeFromSuperview];  

}
@end
